package com.personal.book.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.personal.book.commons.AjaxResponse;
import com.personal.book.dao.BookTypeDao;
import com.personal.book.dao.impl.BookTypeDaoImpl;
import com.personal.book.entity.BookType;
import com.personal.book.service.BookTypeService;
import com.personal.book.service.impl.BookTypeServiceImpl;
import com.personal.tools.PageData;

/**
 * Servlet implementation class BookTypeServlet.
 */
@WebServlet("/BookTypeServlet")
public class BookTypeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	BookTypeDao bookTypeDao = new BookTypeDaoImpl();
	BookTypeService bookTypeService = new BookTypeServiceImpl();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public BookTypeServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置编码
		request.setCharacterEncoding("utf-8");
		response.setContentType("application/json;charset=utf-8");
		BookTypeService service = new BookTypeServiceImpl();
		// 获取op判断做什么操作
		String op = "";
		if (request.getParameter("op") != null) {
			op = request.getParameter("op");
		}
		if ("queryByPage".equals(op)) {
			// 进行查询
			doquery(request, response, service);
		} else if ("add".equals(op)) {
			// 添加
			add(request, response, service);
		} else if ("ajaxchecktitle".equals(op)) {
			// 判断是否重复
			ajax(request, response, service);
		} else if ("queryById".equals(op)) {
			// 按编号查询（修改时回显数据）
			doquerybyid(request, response, service);
		} else if ("update".equals(op)) {
			// 修改
			updatebooktype(request, response, service);
		} else if ("del".equals(op)) {
			// 删除
			doAjaxDel(request, response);
		} else if ("search".equals(op)) {
			doSearch(request, response);
		}
	}

	private void doAjaxDel(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.设置响应头的contentType
		response.setContentType("application/json;charset=utf-8");

		// 先获取请求参数的值
		int typeId = 0;
		if (request.getParameter("typeId") != null) {
			typeId = Integer.parseInt(request.getParameter("typeId"));
		}

		// 2 调用 service的方法
		boolean flag = bookTypeService.Del(typeId);

		AjaxResponse res = new AjaxResponse(flag + "", 200);
		// 3将list转换为json格式的字符串
		Gson gson = new Gson();
		String jsonString = gson.toJson(res);

		// 4 响应
		PrintWriter outPrintWriter = response.getWriter();
		outPrintWriter.print(jsonString);

		// 5.关闭
		outPrintWriter.close();
	}

	/**
	 * 查询
	 * 
	 * @param request
	 * @param response
	 * @param service
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doquery(HttpServletRequest request, HttpServletResponse response, BookTypeService service)
			throws ServletException, IOException {
		// 获取关键字
		String key = "";
		if (request.getParameter("keyname") != null) {
			key = request.getParameter("keyname");
		}
		// 设置初始页数，每页数据数
		int page = 1;
		int pageSize = 10;
		if (request.getParameter("page") != null) {
			page = Integer.parseInt(request.getParameter("page"));
		}
		if (request.getParameter("pageSize") != null) {
			pageSize = Integer.parseInt(request.getParameter("pageSize"));
		}
		// 调用方法
		PageData<BookType> pd = service.getBookTypeByKeyWord(page, pageSize, key + "%");
		// 传值
		request.setAttribute("pd", pd);
		request.setAttribute("key", key);
		// 重定向
		request.getRequestDispatcher("bookTypeInfo.jsp").forward(request, response);
	}

	/**
	 * 按编号查询
	 * 
	 * @param request
	 * @param response
	 * @param service
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doquerybyid(HttpServletRequest request, HttpServletResponse response, BookTypeService service)
			throws ServletException, IOException {
		// 获取id
		int typeId = Integer.parseInt(request.getParameter("typeId"));
		// 调用方法
		BookType bookType = bookTypeDao.getBookTypeById(typeId);
		// 传值
		request.setAttribute("bookType", bookType);
		// 重定向
		request.getRequestDispatcher("bookTypeInfoUpdate.jsp").forward(request, response);
	}

	/**
	 * 关键词模糊查询
	 * 
	 * @param request
	 * @param response
	 * @param service
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doSearch(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获取id
		String keys = null;
		// 设置初始页数，每页数据数

		if (request.getParameter("keyname") != null) {
			keys = request.getParameter("keyname");
		}
		int page = 1;
		int pageSize = 10;
		if (request.getParameter("page") != null) {
			page = Integer.parseInt(request.getParameter("page"));
		}
		if (request.getParameter("pageSize") != null) {
			pageSize = Integer.parseInt(request.getParameter("pageSize"));
		}
		PageData<BookType> pd = bookTypeService.getBookTypeByKeyWord(page, pageSize, keys);

		// 传值
		request.setAttribute("pd", pd);
		// 重定向
		request.getRequestDispatcher("bookTypeInfo.jsp").forward(request, response);
	}

	/**
	 * 添加
	 * 
	 * @param request
	 * @param response
	 * @param service
	 * @throws ServletException
	 * @throws IOException
	 */
	private void add(HttpServletRequest request, HttpServletResponse response, BookTypeService service)
			throws ServletException, IOException {
		// 进行图书类型的添加
		String typeName = request.getParameter("typename");
		String typeDescribe = request.getParameter("typedescribe");
		// 重复提交 -III 增加了一个判断是否为重复提交的操作
		String tokenSession = (String) request.getSession().getAttribute("token");
		String tokenRequest = request.getParameter("token");

		// 重复提交的判断
		if (tokenSession == null || tokenRequest == null || !tokenSession.equals(tokenRequest)) {
			// 重复提交了
			request.setAttribute("msg", "重复提交了!请勿刷新!");
			request.getRequestDispatcher("addBookTypeInfo.jsp").forward(request, response);
		} else {
			BookType bookType = new BookType(typeName, typeDescribe);
			if (service.Add(bookType)) {
				doquery(request, response, service);
			} else {
				request.setAttribute("msg", "类型名重复，请重新输入");
				request.getRequestDispatcher("addBookTypeInfo.jsp").forward(request, response);
			}
		}
	}

	/**
	 * add方法中ajax查询是否重复
	 * 
	 * @param request
	 * @param response
	 * @param service
	 * @throws ServletException
	 * @throws IOException
	 */
	private void ajax(HttpServletRequest request, HttpServletResponse response, BookTypeService service)
			throws ServletException, IOException {
		String typeName = request.getParameter("typename");
		String msg = "类型名不重复可以使用";
		BookType bookType = service.getBookTypeByName(typeName);
		if (bookType != null) {
			msg = "类型名重复不可以使用";
		}
		Gson gson = new Gson();
		String mesg = gson.toJson(msg);
		response.getWriter().print(mesg);
	}

	/**
	 * 修改
	 * 
	 * @param request
	 * @param response
	 * @param service
	 * @throws ServletException
	 * @throws IOException
	 */
	private void updatebooktype(HttpServletRequest request, HttpServletResponse response, BookTypeService service)
			throws ServletException, IOException {
		// 从页面获取数据
		int typeId = Integer.parseInt(request.getParameter("typeId"));
		String typeName = request.getParameter("typename");
		String typeDescribe = request.getParameter("typedescribe");
		BookType booktype = new BookType(typeId, typeName, typeDescribe);
		// 调用方法修改
		bookTypeDao.Update(booktype);
		// 跳转
		response.sendRedirect("bookTypeInfo.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
